package registry

import (
	"dashenwo.com/dashenwo/micro_srv/search_srv/configs"
	"dashenwo.com/dashenwo/micro_srv/search_srv/internal/repository"
	"dashenwo.com/dashenwo/micro_srv/search_srv/internal/repository/impl"
	"dashenwo.com/dashenwo/micro_srv/search_srv/internal/service"
	"github.com/sarulabs/di"
)

type Container struct {
	ctn di.Container
}

func NewContainer() (*Container,error) {
	builder,err := di.NewBuilder()
	if err != nil {
		return nil, err
	}
	if err := builder.Add([]di.Def{
		{
			Name:  "search_service",
			Build: buildUserService,
		},
	}...); err != nil {
		return nil, err
	}
	return &Container{
		ctn: builder.Build(),
	}, nil
}
func (c *Container) Resolve(name string) interface{} {
	return c.ctn.Get(name)
}

func (c *Container) Clean() error {
	return c.ctn.Clean()
}

func buildUserService(ctn di.Container) (interface{}, error) {
	var repo repository.SearchRepository
	// 初始化es客户端
	configs.InitEs()
	// 获取es资源访问类
	repo = impl.NewSearchRepository()
	// 返回服务类
	searchService := service.NewSearchService(repo)
	return searchService, nil
}